package com.bluedot.timer;

import com.bluedot.pojo.pack.PreMappedStatement;
import com.bluedot.pojo.po.Material;
import com.bluedot.pojo.po.MaterialDetail;
import com.bluedot.pojo.po.Report;
import com.bluedot.pojo.po.ReportDetail;
import com.bluedot.service.UtilTool;

import javax.servlet.http.HttpServlet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: dataChargeTimer
 * @Description: TODO
 * @Author: wyk
 * @Date: 2022/8/24 8:49
 **/
public class dataChargeTimer extends HttpServlet {
    private static final UtilTool utilTool = new UtilTool();

    //定时任务
    private static ScheduledExecutorService timer;

    @Override
    public void init() {
        //默认为7天
        runTimer(7L);
    }

    private static void runTimer(Long time) {
        //设置并启动定时任务
        timer = Executors.newScheduledThreadPool(2);
        timer.scheduleAtFixedRate(() -> {
            System.out.println("定时任务执行~");
            Material material = new Material().setState(1);
            Report report = new Report().setReportState(1);

            ArrayList<Material> materialArrayList = new ArrayList<>();
            ArrayList<Report> reportArrayList = new ArrayList<>();

            List<Object> m = utilTool.query(new PreMappedStatement(UtilTool.QUERY, material));
            if (m != null) {
                m.forEach(x -> materialArrayList.add((Material) x));
                materialArrayList.forEach(x -> {
                    Integer materialId = x.getMaterialId();
                    //material表
                    utilTool.delete(new PreMappedStatement(UtilTool.DELETE, new Material(materialId)));
                    //materialDetail表
                    utilTool.delete(new PreMappedStatement(UtilTool.DELETE, new MaterialDetail(materialId)));
                });
            }
            List<Object> r = utilTool.query(new PreMappedStatement(UtilTool.QUERY, report));
            if (r != null) {
                r.forEach(x -> reportArrayList.add((Report) x));
                reportArrayList.forEach(x -> {
                    Integer reportId = x.getReportId();
                    //material表
                    utilTool.delete(new PreMappedStatement(UtilTool.DELETE, new Report(reportId)));
                    //materialDetail表
                    utilTool.delete(new PreMappedStatement(UtilTool.DELETE, new ReportDetail(reportId)));
                });
            }
        }, time, time, TimeUnit.DAYS);

    }

    public static void changeSchedule(Long time) {
        timer.shutdownNow();//停止当前任务
        runTimer(time);//设置新任务
    }

}
